//
//  UIColor + extension.swift
//  czWB
//
//  Created by Qing on 2018/6/1.
//  Copyright © 2018年 成哥哥. All rights reserved.
//

import UIKit

extension UIColor {
    
    
    /// 随机生成颜色
    class var cz_randomColor: UIColor {
        
        let red = CGFloat(arc4random()%256) / 255.0
        let green = CGFloat(arc4random()%256) / 255.0
        let blue = CGFloat(arc4random()%256) / 255.0
        
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }
    
//    /// 把#FFFFF转换成UIColor
//        ///
//    /// - Parameter hex: #ffff
//        /// - Returns: 返回颜色
//        class func WithHex(hex:String) ->UIColor {
//
//            var cString = hex.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines).uppercased()
//
//            if (cString.hasPrefix("#")) {
//                let index = cString.index(cString.startIndex, offsetBy:1)
//                cString = cString.substring(from: index)
//            }
//
//            if (cString.characters.count != 6) {
//                return UIColor.red
//            }
//
//            let rIndex = cString.index(cString.startIndex, offsetBy: 2)
//            let rString = cString.substring(to: rIndex)
//            let otherString = cString.substring(from: rIndex)
//            let gIndex = otherString.index(otherString.startIndex, offsetBy: 2)
//            let gString = otherString.substring(to: gIndex)
//            let bIndex = cString.index(cString.endIndex, offsetBy: -2)
//            let bString = cString.substring(from: bIndex)
//
//            var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
//            Scanner(string: rString).scanHexInt32(&r)
//            Scanner(string: gString).scanHexInt32(&g)
//            Scanner(string: bString).scanHexInt32(&b)
//
//            return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
//        }
//

}


// MARK: - Hex颜色转换为UIColor，这段段友现在还不能理解
extension UIColor {
    
    
    /// 把rgb颜色转成16进制颜色字符串
    var toHexString: String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        
        self.getRed(&r, green: &g, blue: &b, alpha: &a)
        
        return String(
            format: "%02X%02X%02X",
            Int(r * 0xff),
            Int(g * 0xff),
            Int(b * 0xff)
        )
        
    }
    
    
    /// 把16进制颜色转换为RGB颜色
    ///
    /// - Parameter hex: 16进制颜色字符串
    convenience init(hex: String) {
        let scanner = Scanner(string: hex)
        scanner.scanLocation = 0
        
        var rgbValue: UInt64 = 0
        
        scanner.scanHexInt64(&rgbValue)
        
        let r = (rgbValue & 0xff0000) >> 16
        let g = (rgbValue & 0xff00) >> 8
        let b = rgbValue & 0xff
        
        self.init(
            red: CGFloat(r) / 0xff,
            green: CGFloat(g) / 0xff,
            blue: CGFloat(b) / 0xff, alpha: 1
        )
    }
    
}

